/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.machineryrental.restclient;

import cz.muni.fi.pa165.machineryrental.dto.CustomerDTO;
import cz.muni.fi.pa165.machineryrental.restclient.dialogs.CustomerDialog;
import cz.muni.fi.pa165.machineryrental.restclient.dialogs.CustomerSearchDialog;
import cz.muni.fi.pa165.machineryrental.restclient.enums.CustomerSearchType;
import cz.muni.fi.pa165.machineryrental.restclient.services.CustomerRestService;
import cz.muni.fi.pa165.machineryrental.restclient.services.CustomerRestServiceImpl;
import cz.muni.fi.pa165.machineryrental.restclient.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author David Katuscak, 359273
 */
public class CustomersManipulationPanel extends javax.swing.JPanel {

    private List<CustomerDTO> active;

    /**
     * Creates new form CustomersManipulationPanel
     */
    public CustomersManipulationPanel() {
        initComponents();

        this.active = new ArrayList<CustomerDTO>();

        // Creates listener, if has been changed any selected row in table
        customersTable.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                recomputeCanClick();
            }
        });

        this.recomputeCanClick();
        
    }

    /**
     * Enables/disabled remove button and edit button if is any row selected or
     * not.
     */
    private void recomputeCanClick() {

        int selectedRowIndex = customersTable.getSelectedRow();
        System.out.println("Selected row index: " + selectedRowIndex);

        boolean isSelected = selectedRowIndex >= 0;
        removeBtn.setEnabled(isSelected);
        editBtn.setEnabled(isSelected);
    }

    /**
     * Sets data to table
     *
     * @param machines
     */
    private void setToTable(List<CustomerDTO> customers) {

        System.out.println("Count: " + customers.size());
        active.clear();

        recomputeCanClick();

        Utils.clearTable(customersTable);

        for (CustomerDTO customer : customers) {
            this.active.add(customer);
            this.addRow(customer);
        }
    }

    private void addRow(CustomerDTO c) {
        DefaultTableModel model = (DefaultTableModel) customersTable.getModel();
        model.addRow(Utils.toRow(c));
    }

    public void refresh() {

        new SwingWorker<List<CustomerDTO>, Void>() {
            @Override
            protected List<CustomerDTO> doInBackground() {

                try {
                    CustomerRestService customerService = new CustomerRestServiceImpl();
                    return customerService.findAll();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }

                return null;
            }

            @Override
            protected void done() {
                try {
                    List<CustomerDTO> customers = this.get();
                    setToTable(customers);

                } catch (InterruptedException ex) {
                    Logger.getLogger(CustomersManipulationPanel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(CustomersManipulationPanel.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }.execute();
    }

    private void removeActiveRow() {
        if (customersTable.getSelectedRow() < 0) {
            JOptionPane.showMessageDialog(null, "Select any row and repeat operation.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        final CustomerDTO toRemove = active.get(customersTable.getSelectedRow());
        int result = JOptionPane.showConfirmDialog(
                null,
                "Are you sure you want to remove customer: "
                + toRemove.getEmail() + ", " + toRemove.getFirstName() + " " + toRemove.getLastName(),
                "Remove?",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (result == 1) { //No
            return;
        }

        new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() {

                try {
                    CustomerRestService service = new CustomerRestServiceImpl();
                    service.remove(toRemove.getId());
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }

                return null;
            }

            @Override
            protected void done() {
                refresh();
            }
        }.execute();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        refreshBtn = new javax.swing.JButton();
        createBtn = new javax.swing.JButton();
        editBtn = new javax.swing.JButton();
        removeBtn = new javax.swing.JButton();
        searchBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        customersTable = new javax.swing.JTable();

        jToolBar1.setRollover(true);

        refreshBtn.setText("Refresh");
        refreshBtn.setFocusable(false);
        refreshBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        refreshBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        refreshBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                refreshBtnMouseClicked(evt);
            }
        });
        jToolBar1.add(refreshBtn);
        refreshBtn.getAccessibleContext().setAccessibleDescription("");

        createBtn.setText("Create customer");
        createBtn.setFocusable(false);
        createBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        createBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        createBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                createBtnMouseClicked(evt);
            }
        });
        jToolBar1.add(createBtn);

        editBtn.setText("Edit customer");
        editBtn.setFocusable(false);
        editBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        editBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        editBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                editBtnMouseClicked(evt);
            }
        });
        jToolBar1.add(editBtn);

        removeBtn.setText("Remove customer");
        removeBtn.setFocusable(false);
        removeBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        removeBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        removeBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                removeBtnMouseClicked(evt);
            }
        });
        jToolBar1.add(removeBtn);

        searchBtn.setText("Search");
        searchBtn.setFocusable(false);
        searchBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        searchBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        searchBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                searchBtnMouseClicked(evt);
            }
        });
        jToolBar1.add(searchBtn);

        customersTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Firstname", "Lastname", "Email", "Phone", "Address", "Type", "VAT", "Company number"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        customersTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        customersTable.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(customersTable);
        customersTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 781, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void createBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createBtnMouseClicked
        final CustomerDTO added = new CustomerDTO();

        CustomerDialog cd = new CustomerDialog(new JFrame(), true, added, true);
        cd.setVisible(true);

        if (cd.getDialogResult()) {

            new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() {

                    try {
                        CustomerRestService service = new CustomerRestServiceImpl();
                        service.create(added);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    }

                    return null;
                }

                @Override
                protected void done() {
                    refresh();
                }
            }.execute();
        }
    }//GEN-LAST:event_createBtnMouseClicked

    private void editBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_editBtnMouseClicked
        final CustomerDTO toEdit = active.get(customersTable.getSelectedRow());

        CustomerDialog cd = new CustomerDialog(new JFrame(), true, toEdit, false);
        cd.setVisible(true);

        if (cd.getDialogResult()) {

            new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() {

                    try {
                        CustomerRestService service = new CustomerRestServiceImpl();
                        service.update(toEdit);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    }

                    return null;
                }

                @Override
                protected void done() {
                    refresh();
                }
            }.execute();
        }
    }//GEN-LAST:event_editBtnMouseClicked

    private void removeBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeBtnMouseClicked
        removeActiveRow();
    }//GEN-LAST:event_removeBtnMouseClicked

    private void searchBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_searchBtnMouseClicked
        CustomerSearchDialog cd = new CustomerSearchDialog(new JFrame(), true);
        cd.setVisible(true);

        if (cd.getDialogResult()) {

            final CustomerSearchType searchType = cd.getSearchType();
            final String searchPhrase = cd.getSearchValue();

            new SwingWorker<Object, Void>() {
                @Override
                protected Object doInBackground() {

                    try {
                        CustomerRestService service = new CustomerRestServiceImpl();

                        switch (searchType) {
                            case Lastname: {
                                return service.findByLastName(searchPhrase);
                            }
                            case Email: {
                                return service.findByEmail(searchPhrase);
                            }
                            default: {
                                return service.findByCompanyNumber(searchPhrase);
                            }
                        }
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    }
                    return null;
                }

                @Override
                protected void done() {

                    Object data = null;

                    try {
                        data = this.get();
                        if (data == null) {
                            return;
                        }
                    } catch (InterruptedException ex) {
                        Logger.getLogger(MachinesManipulationPanel.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ExecutionException ex) {
                        Logger.getLogger(MachinesManipulationPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    if (searchType == CustomerSearchType.Lastname) {
                        List<CustomerDTO> customers = (List<CustomerDTO>) data;
                        setToTable(customers);
                    } else {
                        active.clear();
                        recomputeCanClick();
                        Utils.clearTable(customersTable);
                        addRow((CustomerDTO) data);
                    }
                }
            }.execute();

        }
    }//GEN-LAST:event_searchBtnMouseClicked

    private void refreshBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_refreshBtnMouseClicked
        refresh();
    }//GEN-LAST:event_refreshBtnMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton createBtn;
    private javax.swing.JTable customersTable;
    private javax.swing.JButton editBtn;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton refreshBtn;
    private javax.swing.JButton removeBtn;
    private javax.swing.JButton searchBtn;
    // End of variables declaration//GEN-END:variables
}
